package com.simple.demo.clone;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;

/**
 * 通过序列化和反序列化实现对象的深度克隆,克隆对象和被克隆对象之间具有不同的内存地址
 */
public class CloneUtil {

    public static <T extends Serializable> T clone(T obj) throws Exception {
        T result = null;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(obj);
        ByteArrayInputStream bins = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream oins = new ObjectInputStream(bins);
        result = (T)oins.readObject();
        return result;
    }
}
